package com.bawei.lookfor2204a.model

import android.content.Context
import android.net.ConnectivityManager
import com.blankj.utilcode.util.SPUtils
import okhttp3.OkHttpClient
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 作者：赵亮
 * 时间：2024/10/15 17:05
 * 功能：网络工具累-最终版
 */
class HttpUtils private constructor() {

    /* 双重校验锁单例模式 */
    companion object {
        val HttpUtils by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
            HttpUtils()
        }
    }

    private val retrofit = Retrofit.Builder()
        .baseUrl("http://10.59.9.24/")
        .addConverterFactory(GsonConverterFactory.create())
        .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
        .client(OkHttpClient.Builder()
            .connectTimeout(5, TimeUnit.MINUTES)
            .writeTimeout(5, TimeUnit.MINUTES)
            .readTimeout(5, TimeUnit.MINUTES)
            .addInterceptor(HttpLoggingInterceptor().apply {
                setLevel(HttpLoggingInterceptor.Level.BODY)
            })
            // 头参拦截器
            .addInterceptor { chain ->
                chain.proceed(
                    chain.request().newBuilder()
                        //.addHeader("userId", SPUtils.getInstance().getInt("userId").toString())
                       // .addHeader("sessionId", SPUtils.getInstance().getString("sessionId"))
                        .addHeader("userId", "1972")
                        .addHeader("sessionId","17296703437751972")
                        .build()
                )
            }
            .build())
        .build()

    val apiService = retrofit.create(ApiService::class.java)

    /**
     * 网络判断
     */
    fun hasNet(context: Context): Boolean {
        val manager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val networkInfo = manager.getNetworkInfo(ConnectivityManager.TYPE_WIFI)
        return networkInfo != null && networkInfo.isConnected
    }
}